package com.spring.aop;


import com.spring.aop.interceptor.*;
import com.spring.factory.BeanFactory;
import com.spring.transaction.TransactionManager;

import java.util.Arrays;
import java.util.List;

/**
 * 事务切面
 */

public class TransactionAdvisor extends Advisor {
	
	private TransactionManager manager;
	
	public TransactionAdvisor(String targetClassName, String targetMethodName, BeanFactory factory) {
		aspectBeanName = "transactionManager";
		this.targetClassName = targetClassName;
		this.targetMethodName = targetMethodName;
		this.factory = factory;
	}
	
	
	public TransactionManager getManager() {
		if (manager == null) {
			manager = factory.getBean("transactionManager", TransactionManager.class);
		}
		return manager;
	}
	
	@Override
	public List<Interceptor> getInterceptors() {
		return Arrays.asList(new BeforeInterceptor(this),
				new AfterInterceptor(this),
				new AfterReturningInterceptor(this),
				new AfterThrowingInterceptor(this));
	}
	
	
	@Override
	public void before() throws Throwable {
		getManager().startTransaction();
	}
	
	@Override
	public void after() throws Throwable {
		getManager().endTransaction();
	}
	
	@Override
	public void afterReturning() throws Throwable {
		getManager().commit();
	}
	
	@Override
	public void afterThrowing() throws Throwable {
		getManager().rollback();
	}
}
